﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace Site_Extractor
{
	public class ForumWalla
	{
		private static string
			_mainLink = "http://forums.walla.co.il/?w=/&all=1",
			_linkPrefix = "http://forums.walla.co.il/?w=/";
		private static Rule
			MessageTopicRule = new Rule("td", "class", "w3b"),
			MessageTextRule = new Rule("td", "class", "w3");

		public static List<string> GetAllForumLinks()
		{
			var res = ForumHandler.GatherAllLinks(_mainLink, isForumMine);
			return res;
		}
		public static List<string> GetAllMessageLinks(string forumLink)
		{
			var res = ForumHandler.GatherAllLinks(forumLink, isMessageMine);
			return res;
		}
		private static bool isForumMine(string link)
		{
			return isMine(link, 5);
		}
		private static bool isMessageMine(string link)
		{
			return isMine(link, 6);
		}
		private static bool isMine(string link, int maxCount)
		{
			if (!link.ToLower().StartsWith(_linkPrefix)) return false;
			int count = 0;
			foreach (char c in link) if (c == '/') count++;
			if (count != maxCount) return false;
			return true;
		}
		private static void GetUniqueId(string messageLink, ref ForumMessage msg)
		{
			if (!isMessageMine(messageLink)) return;
			int i = messageLink.LastIndexOf('/');
			if (i < 0) return;
			long.TryParse(messageLink.Substring(i + 1), out msg.UniqueId);
		}
		public static ForumMessage GetMessage(string messageLink)
		{
			ForumMessage msg = new ForumMessage();

			var page = HtmlDownloader.DownloadPage(new Uri(messageLink), Encoding.GetEncoding("hebrew"));
			var nodes = HtmlDownloader.GetNodes(page);
			var dates = ForumHandler.GetFromString(page, ">תאריך: ", "</td>");
			// "שעה: 14:12"
			// "תאריך: 21/3/2009 שעה: 14:12"
			ForumHandler.GetDate(dates[0], "d/M/yyyy שעה: HH:mm", out msg.Date);
			var topicNode = SiteExtractor.GetNodeByRule(nodes, MessageTopicRule);
			var textNode = SiteExtractor.GetNodeByRule(nodes, MessageTextRule);
			
			msg.Topic =ForumHandler.GetTextFromNode(topicNode);
			msg.Text = ForumHandler.GetTextFromNode(textNode);

			GetUniqueId(messageLink, ref msg);	

			return msg;
		}
	}
}
